package com.zcy.auth.intercepertor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcy.auth.mapper.RolePermissionMapper;
import com.zcy.basic.annotation.PermissionApi;
import com.zcy.basic.data.ContextData;
import com.zcy.basic.enums.HttpStatusCode;
import com.zcy.basic.util.AjaxResult;
import com.zcy.pmp.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <p>
 *  权限拦截: 认证&鉴权
 * </p>
 *
 * @author lucker
 * @date 2023/12/5 14:10
 */

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 判断是否有此请求
        if (handler instanceof HandlerMethod) {
            // 判断是否携带token
            if (token != null && !token.isEmpty()) {
                Employee employee = ContextData.LOGIN_MAP.get(token);
                // 判断该用户是否已登录
                if (employee != null) {
                    // 判断请求是否需要权限
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    Method method = handlerMethod.getMethod();
                    if (method.getAnnotation(PermissionApi.class) == null) {
                        // 不需要权限则放行
                        return true;
                    }
                    // 判断用户是否拥有该权限
                    String sn = handlerMethod.getBeanType().getSimpleName() + ":" + method.getName();
                    if (checkUserPermission(ContextData.LOGIN_MAP.get(token), sn)) {
                        return true;
                    }
                }
            }
            // 未携带token或者未登录或未授权返回需授权响应
            responseError(response, HttpStatusCode.UNAUTHORIZED);

        } else {
            // 返回404响应
            responseError(response, HttpStatusCode.NOT_FOUND);
        }
        return false;
    }

    private void responseError(HttpServletResponse response, HttpStatusCode statusCode) throws IOException {
        response.setHeader("Content-Type","text/html;charset=utf-8");
        response.setStatus(statusCode.getCode());
        String resultJSON = new ObjectMapper().writeValueAsString(AjaxResult.error(statusCode.getZhMessage()));
        response.getWriter().write(resultJSON);
    }

    private boolean checkUserPermission(Employee employee, String sn) {
        List<String> snList = rolePermissionMapper.querySnListByEmployeeId(employee.getId());
        return snList != null && snList.contains(sn);
    }
}
